﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using ThoughtWorks.QRCode.Codec;
namespace bzxxxt.admin.service
{
    public class JsonUtil
    {

        public static string ToJson(object obj) {
            JsonSerializerSettings s = new JsonSerializerSettings();
            s.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            s.NullValueHandling = NullValueHandling.Ignore;
            string json = JsonConvert.SerializeObject(obj, Formatting.None, s);
            return json;
        }
        public static T fromJson<T>(string json) {
            JsonSerializerSettings s = new JsonSerializerSettings();
            s.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            s.NullValueHandling = NullValueHandling.Ignore;
            return JsonConvert.DeserializeObject<T>(json); 
        }
        public static object fromJson(string json, Type type) {
            JsonSerializerSettings s = new JsonSerializerSettings();
            s.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            s.NullValueHandling = NullValueHandling.Ignore;
            return JsonConvert.DeserializeObject(json, type, s);
        }
        public static object fromCodeJson(string json, Type type)
        {
            string str = decode(json);
            JsonSerializerSettings s = new JsonSerializerSettings();
            s.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            s.NullValueHandling = NullValueHandling.Ignore;
            return JsonConvert.DeserializeObject(str, type, s);
        }
        public static string ToCodeJson(object obj)
        {
            JsonSerializerSettings s = new JsonSerializerSettings();
            s.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            s.NullValueHandling = NullValueHandling.Ignore;
            string json = JsonConvert.SerializeObject(obj, Formatting.None, s);
            return code(json);
        }

        public static string code(string str) {
            if (string.IsNullOrEmpty(str))
                return null;
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            return Convert.ToBase64String(bytes);
        }

        public static string decode(string str)
        {
            if(string.IsNullOrEmpty(str))
                return null;
            byte[] outputb = Convert.FromBase64String(str);
            return Encoding.UTF8.GetString(outputb);
        }

        /// <summary>
        /// 过滤字符串
        /// </summary>
        public static string StringFilter(string str)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < str.Length; i++)
            {
                char c = str.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 通过http get方式访问网页链接，传递的参数为网页的url,返回网页的html文档
        /// 默认采用utf-8编码方式访问
        /// </summary>
        /// <param name="url">要访问的网址url</param>
        /// <param name="encoding">访问时采用的编码方式,默认为utf-8</param>
        /// <returns>返回网址url所对应的HTML文档</returns>
        public static string HttpGet(string url, string encoding = "gb2312")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "text/html;charset=" + encoding;            
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();            
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(encoding));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }

        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="strData">要生成的文字或者数字，支持中文。如： "4408810820 深圳－广州" 或者：4444444444</param>
        /// <param name="level">大小：L M Q H</param>
        /// <param name="version">版本：如 8</param>
        /// <param name="scale">比例：如 4</param>
        /// <returns></returns>
        public static string CreateQrCode(string strData, string filename, string level="M", int version=0, int scale=8)
        {
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;

            qrCodeEncoder.QRCodeScale = scale;
            qrCodeEncoder.QRCodeVersion = version;
            switch (level)
            {
                case "L":
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;
                    break;
                case "M":
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                    break;
                case "Q":
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q;
                    break;
                default:
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
                    break;
            }
            //文字生成图片
            Image image = qrCodeEncoder.Encode(strData);
            
            string filepath = HttpContext.Current.Server.MapPath(@"~\admin\images") + "\\" ;
            //如果文件夹不存在，则创建
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);
            filepath += filename + ".jpg";
            FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.Write);
            image.Save(fs, ImageFormat.Jpeg);
            fs.Close();
            image.Dispose();
            return @"/admin/images/" + filename + ".jpg";
        }
    }
}
